﻿package 
{
	import flash.display.MovieClip;
	import flash.net.Socket;
	import flash.events.*;
	import flash.text.TextFieldAutoSize;
	import flash.text.*;
	import fl.transitions.Tween;
	import fl.transitions.easing.*;
	import flash.utils.ByteArray;
	import flash.filters.*;

	public class Main extends MovieClip
	{
		public var ip:String;
		public var tcpsocket:SocketTCP = new SocketTCP();
		public var datagram:DatagramSocketExample = new DatagramSocketExample();
		public var arrayCargas:Array = new Array();
		
		public function Main()
		{
			// constructor code

			datagram.addEventListener("ipRecibida", ipRecibida);
			tcpsocket.addEventListener("onConnect", onConnect);
			tcpsocket.addEventListener("onResponse", onResponse);
			datagram.ask();

			}

			function onResponse(event):void
			{
				var arrayRespuesta:Array;
				arrayRespuesta = tcpsocket.respuesta.split("|");
				var id:int = int(arrayRespuesta[0]);

				switch (id)
				{
					case 2 :
						
						var arrayAux:Array = arrayRespuesta[1].toString().split(";");
						for each (var carga:String in arrayAux){
							var arrayFinal:Array = carga.split(",");
							var cargas:Carga = new Carga(int(arrayFinal[0]), arrayFinal[1]);
							arrayCargas.push(cargas);
							dispatchEvent(new Event("arrayChange"));
						}

						break;
/*					case 3 :
						var arrayGrupos:Array;
						arrayGrupos = arrayRespuesta[1].toString().split(";");
						for each (var grupo:String in arrayGrupos)
						{
							var arrayValores:Array;
							arrayValores = grupo.split(",");
							trace(grupo);
						}
						break;
						*/
				}
			}

			function onConnect(event):void
			{
				trace("conecto");
			}

			function ipRecibida(TimerEvent):void
			{
				tcpsocket.conectar(datagram.getHostIp(), 80);
				error.text = datagram.getHostIp();
			}
			
					private function prenderlampara():void
		{
			tcpsocket.enviarMensaje(crearMensaje(25, 1, 1, 1, 1, 'ID=0,R=\x00,G=\xFF,B=\xFF'));
		}

		private function crearMensaje(Size:int, Version:int, id_componente:int, especializacion:int, accion:int, msg:String):String
		{
			var mensaje:ByteArray = new ByteArray();
			mensaje.writeUTFBytes(String.fromCharCode(Size)+String.fromCharCode(0)+String.fromCharCode(0)+String.fromCharCode(0));
			mensaje.writeUTFBytes(String.fromCharCode(Version)+String.fromCharCode(0)+String.fromCharCode(0)+String.fromCharCode(0));
			mensaje.writeUTFBytes(String.fromCharCode(id_componente)+String.fromCharCode(0)+String.fromCharCode(0)+String.fromCharCode(0));
			mensaje.writeUTFBytes(String.fromCharCode(especializacion)+String.fromCharCode(0)+String.fromCharCode(0)+String.fromCharCode(0));
			mensaje.writeUTFBytes(String.fromCharCode(accion)+String.fromCharCode(0)+String.fromCharCode(0)+String.fromCharCode(0));
			mensaje.writeUTFBytes(msg);
			return mensaje.toString();
		}
		include "Configuraciones.as"

		}

	}
